#!/usr/bin/env python
# encoding: utf-8

import unicodedata
import re

def main(env):
	string = env["context"]["selection"]
	result = []
	l = re.split(r"(?u)\b([a-zA-Z0-9]+[a-zA-Z0-9 ]+[a-zA-Z0-9]+)\b",string)
	isSeparator = True
	for elt in l:
		if isSeparator:
			result.append(elt)
		else:
			words = elt.split()
			hasSomeConvertibleWord = False
			subResult = []
			while words:
				for i in range(len(words),0,-1):
					try:
						subResult.append(unicodedata.lookup(" ".join(words[:i])))
						del words[:i]
						hasSomeConvertibleWord = True
						break
					except KeyError:
						pass
				else:
					word = words.pop(0)
					try:
						if word.upper().startswith("0X"):
							word = unichr(int(word,16))
							hasSomeConvertibleWord = True
						elif env["prefs"]["cwUnicode_decimal"]:
							word = unichr(int(word))
							hasSomeConvertibleWord = True
					except:
						pass
					subResult.append(word)
			result.extend(" ".join(subResult))
		isSeparator = not isSeparator
	return [("replace",env["meta"]["antefix"]+"".join(result))]

